#!/usr/bin/env python3
import sys
sys.path.append('/home/gd/dispatch-system/backend')

from wsgi import create_app
from app.models.user import User
from app.models import db
from sqlalchemy import text

app = create_app()
app.app_context().push()

print('=== 检查工单相关权限 ===')
work_order_perms_query = text("""
    SELECT name, code, module, description 
    FROM permissions 
    WHERE name LIKE 'work_order%' OR code LIKE 'work_order%'
    ORDER BY name
""")
work_order_perms = db.session.execute(work_order_perms_query).fetchall()
print('工单相关权限:')
for perm in work_order_perms:
    print(f'  {perm.name} ({perm.code}) - {perm.description}')

print('\n=== 检查各角色的工单权限 ===')
roles = ['admin', 'manager', 'user', 'worker', 'warehouse_manager']
for role in roles:
    print(f'\n{role} 角色的工单权限:')
    role_perms_query = text("""
        SELECT p.name, p.code 
        FROM permissions p
        JOIN role_permissions rp ON p.id = rp.permission_id
        WHERE rp.role = :role AND (p.name LIKE 'work_order%' OR p.code LIKE 'work_order%')
        AND rp.is_granted = 1
        ORDER BY p.name
    """)
    role_perms = db.session.execute(role_perms_query, {'role': role}).fetchall()
    for perm in role_perms:
        print(f'  {perm.name} ({perm.code})')

print('\n=== 检查测试用户的角色和权限 ===')
test_users = User.query.filter(User.username.in_(['admin', 'user1', 'worker1'])).all()
for user in test_users:
    print(f'\n用户 {user.username} (角色: {user.role}):')
    # 检查用户是否有工单查看权限
    from app.utils.auth import check_user_has_permission
    has_view = check_user_has_permission(user, 'work_order.view')
    has_edit = check_user_has_permission(user, 'work_order.edit')
    print(f'  work_order.view: {has_view}')
    print(f'  work_order.edit: {has_edit}')